package com.lineage.server.clientpackets;

import com.lineage.config.ConfigOther;
import com.lineage.echo.ClientExecutor;
import com.lineage.server.datatables.ItemRestrictionsTable;
import com.lineage.server.datatables.PetItemTable;
import com.lineage.server.datatables.PetTypeTable;
import com.lineage.server.datatables.RecordTable;
import com.lineage.server.datatables.ServerItemGiveTable;
import com.lineage.server.model.Instance.L1ItemInstance;
import com.lineage.server.model.Instance.L1NpcInstance;
import com.lineage.server.model.Instance.L1PcInstance;
import com.lineage.server.model.Instance.L1PetInstance;
import com.lineage.server.model.L1Inventory;
import com.lineage.server.model.L1Object;
import com.lineage.server.model.L1PcInventory;
import com.lineage.server.serverpackets.S_ItemName;
import com.lineage.server.serverpackets.S_ServerMessage;
import com.lineage.server.serverpackets.S_SystemMessage;
import com.lineage.server.serverpackets.ServerBasePacket;
import com.lineage.server.templates.L1Npc;
import com.lineage.server.templates.L1PetItem;
import com.lineage.server.templates.L1PetType;
import com.lineage.server.templates.L1ServerItemGive;
import com.lineage.server.world.World;
import java.util.Iterator;
import java.util.Random;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

public class C_GiveItem extends ClientBasePacket {
  private static final Log _log = LogFactory.getLog(C_GiveItem.class);
  
  private static final String[] receivableImpls = new String[] { "L1Npc", "L1Monster", "L1Guardian", "L1Teleporter", "L1Guard" };
  
  public void start(byte[] decrypt, ClientExecutor client) {
    try {
      read(decrypt);
      L1PcInstance pc = client.getActiveChar();
      if (!pc.isGhost() && 
        !pc.isDead() && 
        !pc.isTeleport() && 
        !pc.isPrivateShop()) {
        int targetId = readD();
        int x = readH();
        int y = readH();
        int itemObjId = readD();
        long count = readD();
        if (count > 2147483647L)
          count = 2147483647L; 
        count = Math.max(0L, count);
        L1Object object = World.get().findObject(targetId);
        if (object == null || !(object instanceof L1NpcInstance))
          return; 
        L1NpcInstance target = (L1NpcInstance)object;
        if (!isNpcItemReceivable(target.getNpcTemplate()))
          return; 
        L1Inventory targetInv = target.getInventory();
        L1PcInventory l1PcInventory = pc.getInventory();
        L1ItemInstance item = l1PcInventory.getItem(itemObjId);
        if (item == null)
          return; 
        if (item.getCount() <= 0L)
          return; 
        if (item.isEquipped()) {
          pc.sendPackets((ServerBasePacket)new S_ServerMessage(141));
          return;
        } 
        if (!item.getItem().isTradable()) {
          pc.sendPackets((ServerBasePacket)new S_ServerMessage(210, item.getItem().getNameId()));
          return;
        } 
        if (item.getBless() >= 128) {
          pc.sendPackets((ServerBasePacket)new S_ServerMessage(210, item.getItem().getNameId()));
          return;
        } 
        if (item.isSeal()) {
          pc.sendPackets((ServerBasePacket)new S_SystemMessage(String.valueOf(item.getLogName()) + "处于绑定状态！"));
          return;
        } 
        if (item.get_time() != null) {
          pc.sendPackets((ServerBasePacket)new S_ServerMessage(210, item.getItem().getNameId()));
          return;
        } 
        if (ItemRestrictionsTable.RESTRICTIONS.contains(Integer.valueOf(item.getItemId()))) {
          pc.sendPackets((ServerBasePacket)new S_ServerMessage(210, item.getItem().getNameId()));
          return;
        } 
        L1ServerItemGive itemGive = ServerItemGiveTable.get().getTemplate(item.getItemId());
        if (!pc.isGm()) {
          if (itemGive == null && !pc.isGm()) {
            pc.sendPackets((ServerBasePacket)new S_ServerMessage(210, item.getItem().getNameId()));
            return;
          } 
          if (!itemGive.ispet() && !pc.isGm()) {
            if (object instanceof L1PetInstance)
              pc.sendPackets((ServerBasePacket)new S_ServerMessage(166, "只能给予宠物")); 
          } else {
            int maxCount = itemGive.get_max();
            if (maxCount > 0 && count > maxCount) {
              pc.sendPackets((ServerBasePacket)new S_ServerMessage(166, 
                    String.valueOf(String.valueOf(item.getName())) + "最多只能给予" + maxCount + "个"));
              return;
            } 
          } 
        } 
        if (!pc.isGm()) {
          if (itemGive == null && !pc.isGm()) {
            pc.sendPackets((ServerBasePacket)new S_ServerMessage(210, item.getItem().getNameId()));
            return;
          } 
          if (!itemGive.ismob() && !pc.isGm()) {
            if (object instanceof com.lineage.server.model.Instance.L1MonsterInstance)
              pc.sendPackets((ServerBasePacket)new S_ServerMessage(210, item.getItem().getNameId())); 
          } else {
            int maxCount = itemGive.get_max();
            if (maxCount > 0 && count > maxCount) {
              pc.sendPackets((ServerBasePacket)new S_ServerMessage(166, 
                    String.valueOf(String.valueOf(item.getName())) + "最多只能给予" + maxCount + "个"));
              return;
            } 
          } 
        } 
        int pcx = pc.getX();
        int pcy = pc.getY();
        if (Math.abs(pcx - x) >= 3 || Math.abs(pcy - y) >= 3) {
          pc.sendPackets((ServerBasePacket)new S_ServerMessage(142));
          return;
        } 
        Iterator<L1NpcInstance> iterator = pc.getPetList().values().iterator();
        while (iterator.hasNext()) {
          Object petObject = iterator.next();
          if (petObject instanceof L1PetInstance) {
            L1PetInstance pet = (L1PetInstance)petObject;
            if (item.getId() == pet.getItemObjId()) {
              pc.sendPackets((ServerBasePacket)new S_ServerMessage(210, item.getItem().getNameId()));
              return;
            } 
          } 
        } 
        if (item.getId() == pc.getQuest().get_step(74)) {
          pc.sendPackets((ServerBasePacket)new S_ServerMessage(210, item.getItem().getName()));
          return;
        } 
        if (pc.getDoll(item.getId()) != null) {
          pc.sendPackets((ServerBasePacket)new S_ServerMessage(1181));
          return;
        } 
        RecordTable.get().recordgivenpc(pc.getName(), item.getAllName(), (int)count, item.getId(), 
            pc.getIp());
        L1ItemInstance getItem = l1PcInventory.tradeItem(item, count, targetInv);
        target.onGetItem(getItem);
        target.turnOnOffLight();
        pc.turnOnOffLight();
        L1PetType petType = PetTypeTable.getInstance()
          .get(target.getNpcTemplate().get_npcId());
        if (petType == null || target.isDead())
          return; 
        if (getItem.getItemId() == petType.getItemIdForTaming())
          tamePet(pc, target); 
        L1PetItem petItem = PetItemTable.get().getTemplate(item.getItemId());
        if (!(target instanceof L1PetInstance))
          return; 
        L1PetInstance tgPet = (L1PetInstance)target;
        if (getItem.getItemId() == petType.getEvolvItemId() && petType.canEvolve()) {
          evolvePet(pc, tgPet);
          return;
        } 
        if (petItem == null)
          return; 
        if (petItem.isWeapom()) {
          C_UsePetItem.usePetWeapon(pc, tgPet, item, petItem);
          return;
        } 
        C_UsePetItem.usePetArmor(pc, tgPet, item, petItem);
        return;
      } 
      return;
    } catch (Exception exception) {
    
    } finally {
      over();
    } 
  }
  
  private boolean isNpcItemReceivable(L1Npc npc) {
    String[] receivableImpls;
    int length = (receivableImpls = C_GiveItem.receivableImpls).length;
    int i = 0;
    while (i < length) {
      String impl = receivableImpls[i];
      if (npc.getImpl().equals(impl))
        return true; 
      i++;
    } 
    return false;
  }
  
  private void tamePet(L1PcInstance pc, L1NpcInstance target) {
    if (target instanceof L1PetInstance || target instanceof com.lineage.server.model.Instance.L1SummonInstance)
      return; 
    int petcost = 0;
    int divisor = 6;
    int petCount = 0;
    Object[] petList = pc.getPetList().values().toArray();
    Object[] array;
    int length = (array = petList).length;
    int i = 0;
    while (i < length) {
      Object pet = array[i];
      int nowpetcost = ((L1NpcInstance)pet).getPetcost();
      petcost += nowpetcost;
      i++;
    } 
    int charisma = pc.getCha();
    if (pc.isCrown()) {
      charisma += 6;
    } else if (pc.isElf()) {
      charisma += 12;
    } else if (pc.isWizard()) {
      charisma += 6;
    } else if (pc.isDarkelf()) {
      charisma += 6;
    } else if (pc.isDragonKnight()) {
      charisma += 6;
    } else if (pc.isIllusionist()) {
      charisma += 6;
    } 
    charisma -= petcost;
    int npcId = target.getNpcId();
    if (npcId == 45313 || npcId == 45710 || npcId == 45711 || npcId == 45712) {
      divisor = 12;
    } else {
      divisor = 6;
    } 
    petCount = charisma / divisor;
    if (petCount <= 0) {
      pc.sendPackets((ServerBasePacket)new S_ServerMessage(489));
      return;
    } 
    L1PcInventory inv = pc.getInventory();
    if (inv.getSize() < 180)
      if (isTamePet(target)) {
        L1ItemInstance petamu = inv.storeItem(40314, 1L);
        if (petamu != null)
          pc.sendPackets((ServerBasePacket)new S_ItemName(petamu)); 
      } else {
        pc.sendPackets((ServerBasePacket)new S_ServerMessage(324));
      }  
  }
  
  private void evolvePet(L1PcInstance pc, L1PetInstance pet) {
    L1PetType petType = PetTypeTable.getInstance().get(pet.getNpcTemplate().get_npcId());
    L1PcInventory inv = pc.getInventory();
    L1ItemInstance petamu = inv.getItem(pet.getItemObjId());
    int level = ConfigOther.PetLevelUp;
    if (pet.getLevel() >= level && pc == pet.getMaster() && petamu != null) {
      pet.getInventory().consumeItem(petType.getEvolvItemId(), 1L);
      L1ItemInstance highpetamu = inv.storeItem(40316, 1L);
      if (highpetamu != null) {
        pet.evolvePet(highpetamu.getId());
        pc.sendPackets((ServerBasePacket)new S_ItemName(highpetamu));
        inv.removeItem(petamu, 1L);
      } 
    } 
  }
  
  private boolean isTamePet(L1NpcInstance npc) {
    boolean isSuccess = false;
    int npcId = npc.getNpcTemplate().get_npcId();
    if (npcId == 45313) {
      Random random = new Random();
      if (npc.getMaxHp() / 3 > npc.getCurrentHp() && random.nextInt(16) == 15)
        isSuccess = true; 
    } else if (npc.getMaxHp() / 3 > npc.getCurrentHp()) {
      isSuccess = true;
    } 
    if ((npcId == 45313 || npcId == 45044 || npcId == 45711) && npc.isResurrect())
      isSuccess = false; 
    return isSuccess;
  }
  
  public String getType() {
    return getClass().getSimpleName();
  }
}
